<template>
	<div class="trade_page layer">
		<div class="trade_page_cont">
			<van-tabs v-model="active" background="transparent" title-active-color="#fff" title-inactive-color="#999"
				line-height="2px" color="#0DF5E3">
				<van-tab :title="$t('trade.ordinary')" name="1">
					<div class="order" @click="$router.push('/order')">{{$t('trade.order')}}</div>
					<div class="cont_box">
						<div class="trade_box" :class="fanZuan ? 'fanZuan' : ''">
							<div>
								<div class="title_box">
									<div class="icon_box" @click="index = 1;hasTokens = !hasTokens">
										<img :src="activeCurr?.source?.icon_img" />
										{{activeCurr?.source?.name}}
										<van-icon name="arrow-down" />
									</div>
									<div class="have_box">
										{{$t('trade.have')}}：{{activeCurr?.source?.balance}}
									</div>
								</div>
								<el-input v-model="input1" @input="(val) => input1 = val.match(/^\d*(\.?\d{0,6})/g)[0]"
									placeholder="0.00"></el-input>
								<div class="min">MIN：{{fanZuan ? activeCurr?.min_to : activeCurr?.min_from}}</div>
							</div>
							<div class="trade_icon" @click="activeCurr.reverse_flag == 1 ? fanZuan = !fanZuan : ''"></div>
							<div>
								<div class="title_box">
									<div class="icon_box" @click="index = 2;hasTokens = !hasTokens">
										<img :src="activeCurr?.dist?.icon_img" />
										{{activeCurr?.dist?.name}}
										<van-icon name="arrow-down" />
									</div>
									<div class="have_box">
										{{$t('trade.have')}}：{{activeCurr?.dist?.balance}}
									</div>
								</div>
								<el-input v-model="input2" @input="(val) => input2 = val.match(/^\d*(\.?\d{0,6})/g)[0]"
									placeholder="0.00"></el-input>
								<div class="min">MIN：{{fanZuan ? activeCurr?.min_from : activeCurr?.min_to}}</div>
							</div>
						</div>
					</div>
				</van-tab>
				<van-tab :title="$t('trade.guild')" name="2">
					<div class="cont_box">
						<div class="guild_info">
							<div class="guild_title">{{$t('trade.current')}}</div>
							<div class="number">
								<span>{{guildInfo.current}}</span> / {{guildInfo.guild_total}}
							</div>
							<div class="guild_max">
								<van-icon name="info-o" />
								{{$t('trade.maxCurrent')}}：{{guildInfo.guild_total}}
							</div>
						</div>
						<div class="trade_box">
							<div class="title_box">
								<div class="icon_box" @click="index = 1;hasTokens = !hasTokens">
									<img :src="activeCurr?.source?.icon_img" />
									{{activeCurr?.source?.name}}
									<van-icon name="arrow-down" />
								</div>
								<div class="have_box">
									{{$t('trade.have')}}：{{activeCurr?.source?.id == 1 ? userInfo.money : activeCurr?.source?.id == 2 ? userInfo.spal : userInfo.spal_legacy}}
								</div>
							</div>
							<el-input v-model="input1" @input="(val) => input3 = val.match(/^\d*(\.?\d{0,6})/g)[0]"
								placeholder="0.00"></el-input>
							<div class="trade_icon"></div>
							<div class="title_box">
								<div class="icon_box" @click="index = 2;hasTokens = !hasTokens">
									<img :src="activeCurr?.dist?.icon_img" />
									{{activeCurr?.dist?.name}}
									<van-icon name="arrow-down" />
								</div>
								<div class="have_box">
									{{$t('trade.have')}}：{{activeCurr?.dist?.id == 1 ? userInfo.money : activeCurr?.dist?.id == 2 ? userInfo.spal : userInfo.spal_legacy}}
								</div>
							</div>
							<el-input v-model="input2" @input="(val) => input4 = val.match(/^\d*(\.?\d{0,6})/g)[0]"
								placeholder="0.00"></el-input>
							<el-divider></el-divider>
							<div class="title_box">
								<div class="icon_box">
									{{$t('trade.guildName')}}
								</div>
							</div>
							<el-input v-model="guildName" class="last"></el-input>
						</div>
					</div>
				</van-tab>
			</van-tabs>
			<el-button class="submit_but" @click="submit">{{$t('trade.exchange')}}</el-button>
			<ChooseTokens v-if="hasTokens" v-model="hasTokens" @change="changeTokens"
				:list="index == 1 ? topList : bottomList" />
			<PassWork v-if="hasShowPass" v-model="hasShowPass" @success="pay" />
		</div>
		<Nav />
	</div>
</template>

<script>
	import ChooseTokens from '../home/components/chooseTokens.vue'
	import PassWork from '@/components/password.vue'
	import {
		indexExchargeList,
		indexExchargeConvert,
		indexExchargeOrder,
		indexExchargeGuild
	} from '@/api/home'

	export default {
		name: 'TradePage',
		components: {
			ChooseTokens,
			PassWork
		},
		data() {
			return {
				hasTokens: false,
				fanZuan: false,
				hasShowPass: false,
				active: '1',
				input1: '',
				input2: '',
				guildName: '',
				activeCurr: {},
				guildInfo: {}, // 工会信息
				config: {},
				topList: [],
				bottomList: [],
			}
		},
		computed: {
			userInfo() {
				return this.$store.state.userInfo
			},
			currencyList() {
				return this.$store.state.currencyList
			}
		},
		watch: {
			// currencyList: {
			// 	handler(val) {
			// 		if (val && val.length > 0) {
			// 			this.activeCurr = val[0]
			// 			this.activeCurr2 = val[1]
			// 		}
			// 	},
			// 	deep: true,
			// 	// immediate: true
			// },
			active(val) {
				this.getConfig()
				this.guildName = ''
				if (val == 2) {
					this.getTrade()
					this.input1 = 30000
				} else {
					this.input1 = ''
					this.input2 = ''
				}
			},
			input1(val) {
				// console.log('val1', val);
				if (this.loading) return
				clearTimeout(this.timeout)
				this.timeout = setTimeout(() => {
					if (val != '') {
						this.handleChange(val, 1)
					}
				}, 300)
			},
			input2(val) {
				// console.log('val2', val);
				if (this.loading) return
				clearTimeout(this.timeout)
				this.timeout = setTimeout(() => {
					if (val != '') {
						this.handleChange(val, 2)
					}
				}, 300)
			},
		},
		mounted() {
			// if (this.currencyList && this.currencyList.length > 0) {
			// 	this.activeCurr = this.currencyList[0]
			// 	this.activeCurr2 = this.currencyList[1]
			// }
			// console.log('userInfo', this.currencyList);
			this.getConfig()
		},
		methods: {
			async getConfig() {
				const res = await indexExchargeList({
					flag: this.active == 1 ? 'user_flag' : 'platform_flag'
				})
				if (res && res.code == 1) {
					// console.log('res：：', res);
					this.config = res.data.map(i => {
						return {
							...i,
							source: {
								...i.source,
								balance: this.currencyList.find(item => item.id == i.source.id)?.balance || 0
							},
							dist: {
								...i.dist,
								balance: this.currencyList.find(item => item.id == i.dist.id)?.balance || 0
							}
						}
					});;
					this.topList = this.deWeightFour(this.config.map(i => i.source))
					this.bottomList = this.deWeightFour(this.config.map(i => i.dist));
					this.activeCurr = this.config[0]
					// console.log('topList', this.config);
					// this.activeCurrTopListMoney = this.currencyList.find(i => i.id == res.data[0].)
				} else {
					this.$toast.fail(res.msg)
				}
				// console.log('res', res);
			},
			async getTrade() {
				const res = await indexExchargeGuild()
				if (res && res.code == 1) {
					this.guildInfo = res.data
				}
			},
			async submit() {
				if (this.activeCurr.reverse_flag == 1 ? !this.input2 : !this.input1) {
					this.$toast(this.$t('home.number'))
					return
				}
				if (!this.userInfo.sec_password) {
					this.$toast(this.$t('trade.pleaseSetPaymentPas'))
					this.$router.push('/transactionPassword')
					return
				} else {
					this.hasShowPass = !this.hasShowPass
				}
			},
			async pay(pas) {
				let input1 = this.$utils.str16hex(this.$utils.accMul(this.input1, 1000000))
				let input2 = this.$utils.str16hex(this.$utils.accMul(this.input2, 1000000))
				// console.log('$$$$$', input1, input2, this.input1, this.input2);
				// return
				const res = await indexExchargeOrder({
					type_PW5mEi3y: this.fanZuan ? 2 : 1,
					excharge_type_haWy5Y5F: this.active,
					excharge_id_D3LDgD35: this.activeCurr.id,
					money_JdM6noqP: this.activeCurr.reverse_flag == 1 ? input2 : input1,
					guild_name: this.guildName,
					sec_password_FaEQHG0G: pas,
				})
				if (res && res.code == 1) {
					this.$toast.success(res.msg)
					this.hasShowPass = false;
					this.input1 = this.input2 = ''
					await this.$store.dispatch('getUserInfo')
				} else {
					this.$toast.fail(res.msg)
					this.hasShowPass = false;
				}
			},
			changeTokens(item) {
				// console.log('changeTokens', item);
				let find = this.config.find(i => i.source.id == item.id)
				// console.log('find', find);
				if (find) {
					this.activeCurr = find
					this.input2 = ''
					this.input1 = ''
				}
				// console.log('activeCurr', this.activeCurr);
				// if (this.index == 1) {
				// 	this.activeCurr = item
				// } else {
				// 	this.activeCurr2 = item
				// }
			},
			async handleChange(val, type) {
				this.loading = true
				// console.log('this', this.activeCurr, val);
				if (type == 1) {
					this.input2 = this.$utils.truncateDecimals(this.$math.divide(val, this.activeCurr.excharge_rate), 6);
				} else {
					this.input1 = this.$utils.truncateDecimals(this.$math.divide(val, 1 / this.activeCurr.excharge_rate), 6 );
				}
				// const res = await indexExchargeConvert({
				// 	type: type,
				// 	excharge_id: this.activeCurr.id,
				// 	money: val
				// }).catch(err => this.loading = false)
				// if (res && res.code == 1) {
				// 	if (type == 1) {
				// 		this.input2 = res.data.amount
				// 	} else {
				// 		this.input1 = res.data.amount
				// 	}
				// } else {
				// 	this.$toast.fail(res.msg)
				// }
				this.$nextTick(() => {
					this.loading = false
				})
			},
			deWeightFour(arr) {
				let data = [];
				arr.forEach(item => {
					if (data.length == 0) {
						data.push(item);
					} else {
						let isDiff = true; //是否不同
						for (let i = 0; i < data.length; i++) {
							let dataItem = data[i];
							if (dataItem.id == item.id) {
								/*集合中已经存在相同数据*/
								isDiff = false;
								break;
							}
						}
						if (isDiff) {
							data.push(item);
						}
					}
				});
				return data
			}
		}
	}
</script>
<style lang="less" scoped>
	.trade_page {
		// height: 100%;
		min-height: 100vh;
		// overflow-y:scroll;
		// -webkit-overflow-scrolling:touch;

		.trade_page_cont {
			position: relative;
			padding-top: 5px;

			.order {
				position: absolute;
				top: 12px;
				right: -5px;
				color: #0DF5E3;
			}

			::v-deep .van-tabs__wrap {
				padding: 0 65px;
			}

			.cont_box {
				padding: 20px 0;

				.trade_box {
					display: flex;
					flex-direction: column;
					padding: 18px 15px;
					background-color: #3D3D3D;
					border-radius: 16px;

					.title_box {
						display: flex;
						justify-content: space-between;
						margin-bottom: 10px;
						align-items: center;

						.icon_box {
							display: flex;
							align-items: center;
							font-size: 16px;
							color: #fff;

							img {
								width: 26px;
								height: 26px;
								margin-right: 10px;
							}

							i {
								margin-left: 5px;
							}
						}

						.have_box {
							color: #999999;
							text-align: left;
							margin-left: 10px;
						}
					}

					::v-deep .el-input__inner {
						height: 52px;
						line-height: 52px;
						background-color: #222222;
						border-radius: 10px;
						color: #fff;
						border: 0;
						margin-bottom: 10px;
						text-align: right;
					}

					.last {
						::v-deep .el-input__inner {
							margin-bottom: 0;
						}
					}

					.min {
						color: #999999;
						text-align: left;
						font-size: 14px;
					}

					.trade_icon {
						width: 26px;
						height: 26px;
						background: url('~@/assets/images/trade/trade.png') no-repeat;
						background-size: 100% 100%;
						margin: 10px auto 20px;
					}

					.el-divider {
						position: relative;
						left: -15px;
						width: calc(100% + 30px);
						background-color: #020202;
						margin: 10px 0 20px;
					}
				}

				.fanZuan {
					display: flex;
					flex-direction: column-reverse;
				}

				.guild_info {
					margin-bottom: 20px;
					text-align: left;

					.guild_title {
						font-size: 16px;
						margin-bottom: 10px;
					}

					.number {
						display: flex;
						align-items: baseline;
						margin-bottom: 5px;

						span {
							font-size: 30px;
							margin-right: 5px;
						}
					}

					.guild_max {
						display: flex;
						align-items: center;

						i {
							font-size: 18px;
							margin-right: 5px;
						}
					}
				}
			}

			.submit_but {
				margin-bottom: 120px;
			}
		}
	}
</style>